/* 封装axios用于发送请求 */
import axios from 'axios'
import store from '@/store'
// import { delToken } from "@/utils/storage";
import { Message } from 'element-ui'
import router from '@/router'

// 创建一个新的axios实例 http://likede2-admin.itheima.net/#/login?redirect=%2Fhome
const request = axios.create({
  baseURL: 'https://likede2-admin.itheima.net/likede/',
  timeout: 5000
})

// 添加请求拦截器
request.interceptors.request.use(
  (config) => {
    // console.log(store.state.user.token)
    config.headers.Authorization = `${store.state.user.token}`
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
request.interceptors.response.use(
  (response) => {
    // if (response.data.status === 401) {
    //   const token = store.state.user.token;
    //   store.state.user.token = "";
    //   delToken(token);
    // }
    return response.data
  },
  (error) => {
    if (error.response) {
      if (error.response.status === 500) {
        Message.error(error.response.data)
        return
      }
      if (error.response.status === 401) {
        Message.error(error.response.data)
        store.commit('user/logout')
        router.push('/login')
        return
      }
    }
    return Promise.reject(error)
  }
)

export default request
